import 'package:duuchin/components/song_card.dart';
import 'package:duuchin/models/song_model.dart';
import 'package:duuchin/services/song_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class SongPage extends StatefulWidget {
  const SongPage({Key key}) : super(key: key);

  @override
  _SongPageState createState() => _SongPageState();
}

class _SongPageState extends State<SongPage> {
  EasyRefreshController _easyRefreshController;
  List<SongItem> _songList = SongList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool error = false;
  String errorMsg = '';

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _getSongs();
  }

  /// 获取数据信息
  Future _getSongs({bool addpush = false}) async {
    try {
      // 获取数据 指定类型
      Map<String, dynamic> result =
          await SongService.getSong(page: page, limit: limit);
      // 将数据转换为实体类
      SongList songListModel = SongList.fromJson(result['data']);
      setState(() {
        hasMore = page * limit < result['total'];
        page++;
        if (addpush) {
          _songList.addAll(songListModel.list);
        } else {
          _songList = songListModel.list;
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    }
  }

  /// 下拉刷新回调
  Future _onRefresh() async{
    page = 1;
    await _getSongs();
    _easyRefreshController.finishRefresh(
        success: true
    );
    _easyRefreshController.resetLoadState();
  }

  /// 上拉加载回调
  Future _onload() async{
    if(hasMore){
      await _getSongs(addpush: true);
    }
    _easyRefreshController.finishLoad(
      noMore: !hasMore
    );
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      controller: _easyRefreshController,
      onRefresh:_onRefresh,
      onLoad: _onload,
      header: ClassicalHeader(),
      footer: ClassicalFooter(),
      child: ListView.builder(
        itemCount: _songList.length,
        itemBuilder: (BuildContext context, int index) {
          return SongCardPage(songItem: _songList[index]);
        },
      ),
    );
  }
}
